package cn.mujiankeji.mbrowser.数据.数据库

import android.content.Context
import androidx.room.AutoMigration
import androidx.room.Database
import androidx.room.DeleteColumn
import androidx.room.DeleteTable
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import androidx.room.migration.AutoMigrationSpec

/**
 * 浏览器数据库
 * 包含所有浏览器相关数据：书签、历史记录、下载任务、搜索引擎、搜索历史等
 */
@Database(
    entities = [
        DBDownload::class,
        DBBookmark::class,
        DBHistory::class,
        DBSearchHistory::class,
        DBSearchEngine::class,
        DBIpv4::class,
        DBIpv6::class,
        DBUserScript::class,
        DBHomeTab::class,
        DBWebsiteConfig::class,
        DBUa::class,
        DBQzm::class,
        DBQzmBag::class,
    ],
    version = 8,
    autoMigrations = [
        AutoMigration(from = 1, to = 2),
        AutoMigration(from = 2, to = 3, spec = AppDatabase.v2_3::class),
        AutoMigration(from = 3, to = 4),
        AutoMigration(from = 4, to = 5),
        AutoMigration(from = 5, to = 6, spec = AppDatabase.v6::class),
        AutoMigration(from = 6, to = 7),
        AutoMigration(from = 7, to = 8),
    ],
    exportSchema = true
)
@TypeConverters(
    搜索引擎项目列表转换器::class,
    UserScriptStringListConverter::class,
    快照类型转换器::class,
)
abstract class AppDatabase : RoomDatabase() {
    abstract fun 下载() : DaoDownload
    abstract fun 书签() : DaoBookmark
    abstract fun 历史() : DaoHistory
    abstract fun 搜索历史(): DaoSearchHistory
    abstract fun 搜索引擎() : DaoSearchEngine
    abstract fun IPv4地址段() : DaoIpv4
    abstract fun IPv6地址段() : DaoIpv6
    abstract fun 用户脚本() : DaoUserScript
    abstract fun 主页标签() : DaoHomeTab
    abstract fun 网站配置() : DaoWebsiteConfig
    abstract fun UA标识() : DaoUa
    abstract fun 快照() : DaoQzm
    abstract fun 快照包() : DaoQzmBag

    @DeleteTable(tableName = "HomePage_Tab")
    class v2_3 : AutoMigrationSpec

    @DeleteColumn(tableName = "DBDownload","id")
    class v6 : AutoMigrationSpec
    
    companion object {
        @Volatile
        private var 实例: AppDatabase? = null


        
        fun 获取实例(上下文: Context): AppDatabase {
            return 实例 ?: synchronized(this) {
                实例 ?: 构建数据库(上下文).also { 实例 = it }
            }
        }
        
        private fun 构建数据库(上下文: Context): AppDatabase {
            return Room.databaseBuilder(
                上下文.applicationContext,
                AppDatabase::class.java,
                "database.db" // 更改数据库名称，避免与旧数据冲突
            )

            .build()
        }
    }
} 